﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint.Administration;

using SPaDevToolkit.Diagnostics;

namespace SPaDevToolkit.Administration
{
    public abstract class SPaWebServiceFactory<S, SP, SI, SA, SAP> 
        where S: SPIisWebService    
        where SP : SPIisWebServiceProxy
        where SI : SPIisWebServiceInstance
        where SA : SPIisWebServiceApplication
        where SAP : SPIisWebServiceApplicationProxy
    {
        private SPWebService _AdminService;
        public SPaWebServiceFactory(SPWebService adminService)
        {
            _AdminService = adminService;
        }

        public SPWebService AdminService
        {
            get { return _AdminService; }
        }

        public abstract S CreateService();

        public abstract SP CreateServiceProxy(string name);

        public abstract SI CreateServiceInstance(string name, SPServer server, S service);

        public void RemoveObject(SPPersistedObject obj)
        {
            RemoveObject(obj, true);
        }

        public void RemoveObject(SPPersistedObject obj, bool raiseException)
        {
            try
            {
                if (obj != null)
                {
                    if (obj.Status == SPObjectStatus.Online)
                        obj.Unprovision();

                    obj.Delete();
                }
            }
            catch (Exception ex)
            {
                //Logger.WriteException(ex, string.Format("Error removing persisted object from farm: Name={0}, Id={1}. TypeName={2}", obj.Name, obj.Id, obj.TypeName), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                if (raiseException)
                    throw ex;
            }
        }

        public void DeleteServiceFromFarm()
        {
            SP serviceProxy = _AdminService.Farm.ServiceProxies.GetValue<SP>();
            if (serviceProxy != null)
            {
                try
                {
                    serviceProxy.Unprovision();
                    serviceProxy.Delete();
                }
                catch (Exception ex)
                {
                    //Logger.WriteException(ex, string.Format("An error occured removing the service proxy '{0}' during feature deactivation. Deactivation canceled", serviceProxy.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                    throw;
                }
            }
            S service = _AdminService.Farm.Services.GetValue<S>();
            if (service != null)
            {
                foreach (SI serviceInstance in service.Instances)
                {
                    //TODO: Check status before unprovisioning. Handle exceptions and try to delete
                    RemoveServiceInstance(serviceInstance);
                }
                RemoveObject(service);
            }
        }

        public void RemoveServiceAndAllDependentObjects()
        {
            if (SPFarm.Local == null)
            {
                //Logger.WriteLog("SPFarm.Local returned null during feature deactivation. Deactivation canceled", 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                throw new InvalidOperationException("No farm object available");
            }

            S service = _AdminService.Farm.Services.GetValue<S>();

            if (service == null)
            {
                //Logger.WriteLog("No S object found during feature deactivation. Deactivation canceled", 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                throw new InvalidOperationException("No service object available");
            }

            foreach (SPServiceProxy serviceProxy in SPFarm.Local.ServiceProxies)
            {
                if (serviceProxy is SP)
                {
                    foreach (SPServiceApplicationProxy serviceApplicationProxy in serviceProxy.ApplicationProxies)
                    {
                        if (serviceApplicationProxy is SAP)
                        {
                            try
                            {
                                RemoveObject(serviceApplicationProxy);
                            }
                            catch (Exception ex)
                            {
                                //Logger.WriteException(ex, string.Format("An error occurred removing a service application proxy '{0}' during feature deactivation. Deactivation canceled", serviceApplicationProxy.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                                throw;
                            }
                        }
                    }

                    try
                    {
                        RemoveObject(serviceProxy);
                    }
                    catch (Exception ex)
                    {
                        //Logger.WriteException(ex, string.Format("An error occurred removing the service proxy '{0}' during feature deactivation. Deactivation canceled", serviceProxy.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                        throw;
                    }
                }
            }

            //Remove service instances
            RemoveServiceInstances(service, true);

            foreach (SPServiceApplication serviceApplication in service.Applications)
            {
                if (serviceApplication is SA)
                {
                    try
                    {
                        RemoveObject(serviceApplication);
                    }
                    catch (Exception ex)
                    {
                        //Logger.WriteException(ex, string.Format("An error occurred removing a service application '{0}' during feature deactivation. Deactivation canceled", serviceApplication.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                        throw;
                    }
                }
            }

            try
            {
                RemoveObject(service);
            }
            catch (Exception ex)
            {
                //Logger.WriteException(ex, string.Format("An error occurred removing the service '{0}' during feature deactivation. Deactivation canceled", service.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                throw;
            }
        }

        public void RemoveServiceInstances(S service, bool raiseException)
        {
            foreach (SPServiceInstance serviceInstance in service.Instances)
            {
                if (serviceInstance is SI)
                {
                    try
                    {
                        //Delete service instance job defintions
                        RemoveServiceInstance(serviceInstance, raiseException);
                    }
                    catch (Exception ex)
                    {
                        //Logger.WriteException(ex, string.Format("An error occurred removing a service instance '{0}' during feature deactivation. Deactivation canceled", serviceInstance.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                        if (raiseException)
                            throw;
                    }
                }
            }
        }

        public void RemoveServiceInstance(SPServiceInstance serviceInstance)
        {
            RemoveServiceInstance(serviceInstance, true);
        }

        public void RemoveServiceInstance(SPServiceInstance serviceInstance, bool raiseException)
        {
            var serviceInstanceTimerJobs = _AdminService.Farm.TimerService.JobDefinitions.Where(j => j.Name.ToLower() == "job-service-instance-" + serviceInstance.Id.ToString().ToLower());
            foreach (var job in serviceInstanceTimerJobs)
            {
                try
                {
                    SPServiceInstanceJobDefinition serviceInstanceTimerJob = job as SPServiceInstanceJobDefinition;
                    RemoveObject(serviceInstanceTimerJob, raiseException);
                }
                catch (Exception ex)
                {
                    //Logger.WriteException(ex, string.Format("An error occurred removing a service instance timer job '{0}' for service instance {1} during feature deactivation. Deactivation canceled", job.Name, serviceInstance.Name), 0, EventSeverity.Error, AreaNames.ProductCatalog, CategoryNames.Service);
                    if (raiseException)
                        throw;
                }
            }
            RemoveObject(serviceInstance, raiseException);
        }

    }
}
